#import "ADSlave.h"
#import "ADController.h"
#import "TVController.h"
#import "strfunc.h"

#define  WinBufSIZE	4

static id windowBuffer[WinBufSIZE];
static int	wbp = 0;

@implementation ADSlave

- init:sender with:controller dir:(const char *)path
{
	adCtrl = sender;
	tvCtrl = controller;
	directory = str_dup(path);
	return self;
}

- free
{
	free((void *)directory);
	[super free];
	return nil;
}

- donext: sender
{
	const char *nextfile;
	char	fn[MAXFILENAMELEN];
	id	tw, oldtw, win;
	int	n;

	if ((nextfile = [adCtrl nextFilename]) == NULL) {
		[adCtrl continueLoop:NO];
		return nil;
	}
	sprintf(fn, "%s/%s", directory, nextfile);
	if ([tvCtrl isOpened: fn]) { /* already opened */
		[adCtrl continueLoop:YES];
		return self;
	}
	n = getExtension(nextfile);
	tw = [tvCtrl drawFile: fn : &nextfile[n]];
	if (tw) {
		oldtw = windowBuffer[wbp];
		if (oldtw != nil && [tvCtrl checkWindow:oldtw delete:NO]) {
			win = [oldtw window];
			if ([win counterpart] == nil)
				/* has not been miniaturized */
				[win performClose: self];
		}
		windowBuffer[wbp] = tw;
		wbp = (wbp + 1) % WinBufSIZE;
	}
	[adCtrl continueLoop:YES];
	return self;
}

@end
